//
//  DetailsViewController.m
//  IntimateGift
//
//  Created by zh on 14/12/19.
//  Copyright (c) 2014年 蔡宏业. All rights reserved.
//

#import "DetailsViewController.h"
#import "MBProgressHUD.h"
#import "UIColor+AddColor.h"
//#import <ShareSDK/ShareSDK.h>
#import "DataBaseHandler.h"
#import "BannerGift.h"
#import "AllGroup.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import "UIImageView+WebCache.h"
#import "MyButton.h"


@interface DetailsViewController () <UIWebViewDelegate, UIAlertViewDelegate, UIScrollViewDelegate>
// 加载内容的webView
@property (nonatomic, retain) UIWebView *myWebView;
@property (nonatomic, retain) NSMutableArray *arr;
// 加载等候
@property (nonatomic, retain) MBProgressHUD *HUD;
// 加载等候
@property (nonatomic, retain) UIActivityIndicatorView *actIV;
// 加载时的view
@property (nonatomic, retain) UIView *loadingView;
// 登陆状态
@property (nonatomic, assign) BOOL state;
//标题scrollView
@property (nonatomic, retain)UIScrollView *scrollView;
//标题imageView
@property (nonatomic ,retain)UIImageView *imageview;
//标题laebl
@property (nonatomic, retain)UILabel *titleLaebl;
@property (nonatomic, retain)UILabel *smallLabel;
@property (nonatomic, retain)UILabel *naviLaebl;

@end

@implementation DetailsViewController

- (void)dealloc
{
    
    [_banner release];
    [_choiceness release];
    [_myWebView release];
    [_arr release];
    [_HUD release];
    [_actIV release];
    [_loadingView release];
    [_group release];
    [_scrollView release];
    [_imageview release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
//        self.state = NO;
//        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//        [center addObserver:self selector:@selector(receiveNotifica:) name:@"tamenlaile" object:nil];
    }
    return self;
}

//- (void)receiveNotifica:(NSNotification *)center
//{
//    self.state = YES;
//}

- (void)MBHUD
{
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"努力加载中";
    // 调用block
    [self.HUD showAnimated:YES whileExecutingBlock:^{
        NSLog(@"111111");
        [self doTask];
    } completionBlock:^{
        [self.HUD removeFromSuperview];
        [self.HUD release];
    }];
    self.HUD.yOffset = 0.f;
}


// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    self.actIV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.actIV.frame = CGRectMake(0, 0, 32, 32);
    
    // 设置菊花在视图中心位置
    self.actIV.center = self.loadingView.center;
    [self.loadingView addSubview:self.actIV];
    
    // 菊花开始转动
    [self.actIV startAnimating];
    [_actIV release];
}
// 完成加载
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    // 停止转动
    [self.actIV stopAnimating];
    // 将loadingView移除
    [self.loadingView removeFromSuperview];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"刚开始？？？");
//    NSLog(@"~~~~~%f", scrollView.contentOffset.y);
    if (scrollView == self.myWebView.scrollView) {
       
        if (scrollView.contentOffset.y < -65) {
            
             self.scrollView.frame = CGRectMake(0, -0.25 * self.view.bounds.size.height - (scrollView.contentOffset.y + 0.25 * self.view.bounds.size.height), [UIScreen mainScreen].bounds.size.width, self.view.frame.size.height / 1.8 );
                NSLog(@"--------%f", self.scrollView.frame.origin.y);
//            self.titleLaebl.alpha = (-65  - scrollView.contentOffset.y) / (0.3 * self.view.bounds.size.height);
//            self.smallLabel.alpha =1 - (-65 + 60 - scrollView.contentOffset.y) / (0.3 * self.view.bounds.size.height);
            self.titleLaebl.alpha = (-65 - scrollView.contentOffset.y) / (self.view.bounds.size.height * 0.25 - 65);
            self.smallLabel.alpha = 1 - (-65 - scrollView.contentOffset.y) / (self.view.bounds.size.height * 0.25 - 65);
        }
    }
    NSLog(@"%f", scrollView.contentOffset.y);
}
- (void)viewDidLoad {
//    NSLog(@"%@",self.webDeatil.title);
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
   // self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.alpha = 0.001;
    //self.navigationController.navigationBar.hidden = YES;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigation_bar_background.png"] forBarMetrics:UIBarMetricsDefault];
//    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    self.myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - self.view.bounds.size.height * 0.08)];
    [self.view addSubview:self.myWebView];
    self.myWebView.scrollView.contentInset = UIEdgeInsetsMake(0.25 * self.view.bounds.size.height, 0, 0, 0);
    self.myWebView.delegate = self;
    self.myWebView.scrollView.delegate = self;
    [_myWebView release];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, - 0.25 * self.view.bounds.size.height, self.view.bounds.size.width, self.view.bounds.size.height / 2.0)];
    //self.scrollView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:self.scrollView];
    [_scrollView release];
    
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height / 2.0)];
    [self.scrollView addSubview:imageView];
   // imageView.backgroundColor = [UIColor yellowColor];
    [imageView release];
    self.titleLaebl = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height / 2.0 - 70, self.view.bounds.size.width, 70)];
    imageView.userInteractionEnabled = YES;
    [imageView addSubview:self.titleLaebl];
   
    [_titleLaebl release];
    self.smallLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 10, self.view.bounds.size.width - 70, 60)];
    self.smallLabel.font = [UIFont boldSystemFontOfSize:15];
    self.smallLabel.numberOfLines = 0;
    [self.view addSubview:self.smallLabel];
    self.smallLabel.textColor = [UIColor whiteColor];
    [_smallLabel release];
    self.smallLabel.alpha = 0;
    self.naviLaebl = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 70, 60)];
    [self.view addSubview:self.naviLaebl];
    self.naviLaebl.textColor = [UIColor whiteColor];
    self.naviLaebl.font = [UIFont boldSystemFontOfSize:17];
    self.naviLaebl.userInteractionEnabled = YES;
    //[_naviLaebl release];
    
    
//    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    collectButton.frame = CGRectMake(0, 0, self.view.bounds.size.width / 2 - 1, self.view.bounds.size.height * 0.08);
//    [bigImageView addSubview:collectButton];
//    [collectButton setBackgroundColor:[UIColor ownColor]];
//    [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
//    collectButton.tintColor = [UIColor whiteColor];
//    [collectButton addTarget:self action:@selector(collectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

    
    
    UIImageView *naviImageView = [[UIImageView alloc] initWithFrame:CGRectMake(-2, 31, 25, 20)];
    [self.view addSubview:naviImageView];
    naviImageView.image = [UIImage imageNamed:@"iconfont-xiangzuo.png"];
    naviImageView.userInteractionEnabled = YES;
    [naviImageView release];
    MyButton *naviButton = [MyButton buttonWithType:UIButtonTypeSystem];
    naviButton.frame =CGRectMake(0, 20, 75, 40);
    [self.view addSubview:naviButton];
    naviButton.backgroundColor = [UIColor clearColor];
    [naviButton addTarget:self action:@selector(buttonNaviClick:) forControlEvents:UIControlEventTouchUpInside];
    //[naviButton setTitle:nil forState: UIControlStateNormal];
    //self.navigationController.navigationBar.translucent = YES;
    
    
    
    
        if (self.mark == 1) {
        self.navigationItem.title = @"百元好礼以内也能送好礼";
           
        NSString *str = [NSString stringWithFormat:@"http://www.liwushuo.com/posts/%@/content",[self.banner.target_id description]];
//        NSLog(@"%@",self.banner.target_id);
//        NSString *str = self.banner.content_url;
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        // 加载请求
        [self.myWebView loadRequest:request];
        self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.loadingView.backgroundColor = [UIColor blackColor];
        self.loadingView.alpha = 0.2;
        [self.view addSubview:self.loadingView];
        [_loadingView release];
        
    } else if(self.mark == 2){
        self.navigationItem.title = self.group.title;
        
        // 网络请求
        NSString *str = self.group.content_url;
        //        NSLog(@"%@", self.choiceness.url);
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        // 加载请求
        [self.myWebView loadRequest:request];
        self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.loadingView.backgroundColor = [UIColor blackColor];
        self.loadingView.alpha = 0.2;
        [self.view addSubview:self.loadingView];
        [_loadingView release];

    } else if (self.mark == 3) {
        self.navigationItem.title = @"送好礼";
        
        // 网络请求
        NSString *str = self.banner.content_url;
        //        NSLog(@"%@", self.choiceness.url);
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        // 加载请求
        [self.myWebView loadRequest:request];
        self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.loadingView.backgroundColor = [UIColor blackColor];
        self.loadingView.alpha = 0.2;
        [self.view addSubview:self.loadingView];
        [_loadingView release];
    }
        else {
        self.navigationItem.title = self.choiceness.title;
        // 网络请求
//        NSString *str = [NSString stringWithFormat:@"%@/content", self.choiceness.url];
        
        
        NSString *str = self.choiceness.content_url;
        NSLog(@"%@", self.choiceness.url);
        str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:str];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
        // 加载请求
        [self.myWebView loadRequest:request];
        self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.loadingView.backgroundColor = [UIColor blackColor];
        self.loadingView.alpha = 0.2;
        [self.view addSubview:self.loadingView];
        [_loadingView release];
    }
    
    
    
    
    if (self.mark == 1) {
        [imageView setImageWithURL:[NSURL URLWithString:self.banner.image_url] placeholderImage:[UIImage imageNamed:@"Left.jpg"]];
        [imageView setImageWithURL:[NSURL URLWithString:self.banner.image_url]];
        self.smallLabel.text = self.banner.title;
        self.titleLaebl.text = self.banner.title;
        self.titleLaebl.textColor = [UIColor whiteColor];
        self.titleLaebl.numberOfLines = 0;
        self.titleLaebl.font = [UIFont boldSystemFontOfSize:23];
        self.naviLaebl.text = @"精选";
    
    }else if (self.mark == 2) {
        [imageView setImageWithURL:[NSURL URLWithString:self.group.cover_image_url] placeholderImage:[UIImage imageNamed:@"Left.jpg"]];
        [imageView setImageWithURL:  [NSURL URLWithString:self.group.cover_image_url]];
        self.naviLaebl.text = self.group.name;
        NSLog(@"%@", self.group.name);
        self.smallLabel.text = self.group.title;
        self.titleLaebl.text = self.group.title;
        self.titleLaebl.textColor = [UIColor whiteColor];
        self.titleLaebl.numberOfLines = 0;
        self.titleLaebl.font = [UIFont boldSystemFontOfSize:23];
    }else if (self.mark == 3) {
        [imageView setImageWithURL:[NSURL URLWithString:self.banner.cover_image_url]];
        self.smallLabel.text = self.banner.title;
        self.titleLaebl.text = self.banner.title;
        self.titleLaebl.textColor = [UIColor whiteColor];
        self.titleLaebl.numberOfLines = 0;
        self.titleLaebl.font = [UIFont boldSystemFontOfSize:23];
        self.naviLaebl.text = @"精选";
    }else{
        [imageView setImageWithURL:[NSURL URLWithString:self.choiceness.cover_image_url] placeholderImage:[UIImage imageNamed:@"Left.jpg"]];
        [imageView setImageWithURL:[NSURL URLWithString:self.choiceness.cover_image_url]];
        self.titleLaebl.text = self.choiceness.title;
        self.naviLaebl.text = @"精选";

        self.titleLaebl.textColor = [UIColor whiteColor];
        self.titleLaebl.font = [UIFont boldSystemFontOfSize:23];
        self.titleLaebl.numberOfLines = 0;
        self.smallLabel.text = self.choiceness.title;
}

    // 收藏按钮
//    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(barButtonItemClicked:)] autorelease];
    
    
    
    UIImageView *bigImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - self.view.bounds.size.height * 0.08 , self.view.bounds.size.width, self.view.bounds.size.height * 0.08)];
    [self.view addSubview:bigImageView];
    bigImageView.alpha = 0.75;
    bigImageView.backgroundColor = [UIColor clearColor];
    bigImageView.userInteractionEnabled = YES;
    
    UIButton *collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    collectButton.frame = CGRectMake(0, 0, self.view.bounds.size.width / 2 - 1, self.view.bounds.size.height * 0.08);
    [bigImageView addSubview:collectButton];
    [collectButton setBackgroundColor:[UIColor ownColor]];
    [collectButton setTitle:@"收藏" forState:UIControlStateNormal];
    collectButton.tintColor = [UIColor whiteColor];
    [collectButton addTarget:self action:@selector(collectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    shareButton.frame = CGRectMake(self.view.bounds.size.width / 2 + 1, 0, self.view.bounds.size.width / 2, self.view.bounds.size.height * 0.08);
    shareButton.backgroundColor = [UIColor ownColor];
    [shareButton setTitle:@"分享" forState:UIControlStateNormal];
    shareButton.tintColor = [UIColor whiteColor];
    [bigImageView addSubview:shareButton];
    [shareButton addTarget:self action:@selector(shareButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
        // Do any additional setup after loading the view.
}


- (void)buttonNaviClick:(UIButton *)button
{
    NSLog(@"!!!!!");
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)collectButtonClicked:(UIButton *)button
{
    NSLog(@"收藏");
    NSLog(@"是撒");
    DataBaseHandler *dataHandler = [DataBaseHandler shareInstance];
    
    NSString *str = [NSSearchPathForDirectoriesInDomains
                     (NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@",str);
    
    if (self.mark == 1) {
        [dataHandler  openDB];
        [dataHandler createBannerGiftTable];
        BannerGift *bannerGift = [[BannerGift alloc] init];
        
        bannerGift.title = @"送好礼";
        bannerGift.content_url = [NSString stringWithFormat:@"http://www.liwushuo.com/posts/%@/content",[self.banner.target_id description]];
        bannerGift.cover_image_url = self.banner.image_url;
        NSLog(@"%@", bannerGift.cover_image_url);
        [dataHandler insertBannerGift:bannerGift];
        [bannerGift release];
    }else if (self.mark == 2){
        [dataHandler  openDB];
        [dataHandler createAllGroupTable];
        AllGroup *allGroup = [[AllGroup alloc] init];
        allGroup.title = self.group.title;
        allGroup.content_url = self.group.content_url;
        allGroup.cover_image_url = self.group.cover_image_url;
        [dataHandler insertAllGroup:allGroup];
        [allGroup release];
    }else{
        [dataHandler  openDB];
        [dataHandler createChoicenessTable];
        Choiceness *choiceness = [[Choiceness alloc] init];
        choiceness.title = self.choiceness.title;
        choiceness.content_url = self.choiceness.content_url;
        choiceness.cover_image_url = self.choiceness.cover_image_url;
        [dataHandler insertChoiceness:choiceness];
        [choiceness release];
    }

}

- (WBMessageObject *)messageToShare
{
    if (self.mark == 1) {
        WBMessageObject *message = [WBMessageObject message];
        NSString *str = [NSString stringWithFormat:@"送好礼http://www.liwushuo.com/posts/%@/content",[self.banner.target_id description]];
        message.text = str;
        WBImageObject *image = [WBImageObject object];
        NSString *path = self.banner.image_url;
        NSURL *url = [NSURL URLWithString:path];
        image.imageData = [NSData dataWithContentsOfURL:url];
        message.imageObject = image;
        return message;
    } else if (self.mark == 2) {
        WBMessageObject *message = [WBMessageObject message];
        NSString *str = [NSString stringWithFormat:@"%@%@",self.group.title ,self.group.content_url];
        message.text = str;
        WBImageObject *image = [WBImageObject object];
        NSString *path = self.group.cover_image_url;
        NSURL *url = [NSURL URLWithString:path];
        image.imageData = [NSData dataWithContentsOfURL:url];
        message.imageObject = image;
        return message;
        
        
       

    } else {
        WBMessageObject *message = [WBMessageObject message];
        NSString *str = [NSString stringWithFormat:@"%@%@/content", self.choiceness.title, self.choiceness.url];
        message.text = str;
        WBImageObject *image = [WBImageObject object];
        NSString *path = self.choiceness.cover_image_url;
        NSURL *url = [NSURL URLWithString:path];
        image.imageData = [NSData dataWithContentsOfURL:url];
        message.imageObject = image;
        return message;
        
        

    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = YES;
   
}
- (void)shareButtonClicked:(UIButton *)button
{
//    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录后分享" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//    [alertView show];
//    [alertView release];
//    if (self.state == YES) {
    
        AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
        
        WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
        authRequest.redirectURI = @"http://open.weibo.com";
        authRequest.scope = @"all";
        
        WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare] authInfo:authRequest access_token:myDelegate.wbtoken];
        request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                             @"Other_Info_1": [NSNumber numberWithInt:123],
                             @"Other_Info_2": @[@"obj1", @"obj2"],
                             @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
        //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
        [WeiboSDK sendRequest:request];
//    }
}

//- (void)logoutButton:(UIButton *)button
//{
////    [ShareSDK cancelAuthWithType:ShareTypeSinaWeibo];
//    [self.navigationController popViewControllerAnimated:YES];
//}

- (void)barButtonItemClicked:(UIBarButtonItem *)item
{
    NSLog(@"收藏");
    
}

-(void) doTask{
    // 要进行的一些逻辑操作
    // sleep函数  参数：延迟的秒数
    sleep(5);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
